const { webContents } = require("electron");

/**
 * StorageController 类
 * 提供设置 LocalStorage 和 SessionStorage 的方法
 */
class StorageController {

  setBothStorage(params) {
    // 参数防御：确保 params 是对象且非 null
    if (typeof params !== 'object' || params === null) {
      console.warn('Invalid params provided to setBothStorage');
      return;
    }
  
    const storageMethods = ['setLocalStorage', 'setSessionStorage'];
  
    storageMethods.forEach(method => {
      try {
        if (typeof this[method] === 'function') {
          this[method](params);
        } else {
          console.warn(`Storage method ${method} is not defined`);
        }
      } catch (error) {
        console.error(`Failed to execute ${method}:`, error);
      }
    });
  }

  /**
   * 设置 LocalStorage
   * @param {Object} params - 参数对象
   * @param {string} params.url - 存储的 URL
   * @param {string} params.key - LocalStorage 的键
   * @param {string} params.value - LocalStorage 的值
   * @returns {Promise<boolean>} - 操作成功返回 true
   * @throws {Error} - 缺少必需字段或目标页面未找到
   */
  async setLocalStorage({ url, key, value }) {
    return this._setStorage({ url, key, value }, 'localStorage');
  }

  /**
   * 设置 SessionStorage
   * @param {Object} params - 参数对象
   * @param {string} params.url - 存储的 URL
   * @param {string} params.key - SessionStorage 的键
   * @param {string} params.value - SessionStorage 的值
   * @returns {Promise<boolean>} - 操作成功返回 true
   * @throws {Error} - 缺少必需字段或目标页面未找到
   */
  async setSessionStorage({ url, key, value }) {
    return this._setStorage({ url, key, value }, 'sessionStorage');
  }

  /**
   * 通用设置 storage 方法
   * @private
   */
  async _setStorage({ url, key, value }, storageType) {
    // 验证必需字段
    if (!url || !key || typeof value !== 'string') {
      throw new Error("Missing required fields: url (string), key (string), value (non-empty string)");
    }

    // 查找匹配的目标页面
    const targetPage = this._findWebContentsByUrl(url);
    if (!targetPage) {
      throw new Error(`No page found matching the specified URL: ${url}`);
    }

    // 构造安全的脚本
    const safeKey = JSON.stringify(key);
    const safeValue = JSON.stringify(value);

    const script = `
      if (typeof ${storageType} !== 'undefined') {
        ${storageType}.setItem(${safeKey}, ${safeValue});
        true;
      } else {
        false;
      }
    `;

    try {
      const result = await targetPage.executeJavaScript(script, true);
      if (!result) {
        throw new Error(`${storageType} is not available in the target page.`);
      }
      return true;
    } catch (error) {
      throw new Error(`Failed to execute script on target page: ${error.message}`);
    }
  }

  /**
   * 根据 URL 模糊查找对应的 WebContents 实例
   * @param {string} targetUrl - 目标 URL
   * @returns {WebContents|null} - 匹配的页面实例或 null
   */
  _findWebContentsByUrl(targetUrl) {
    const pages = webContents.getAllWebContents();
    return (
      pages.find((page) => {
        const currentUrl = page.getURL();
        // 判断目标 URL 是否是当前页面 URL 的前缀（模糊匹配）
        return currentUrl.startsWith(targetUrl);
      }) || null
    );
  }
}

StorageController.toString = () => "[class StorageController]";

module.exports = StorageController;